package com.gem.talkbase.activity;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import net.tsz.afinal.FinalHttp;
import net.tsz.afinal.http.AjaxCallBack;
import net.tsz.afinal.http.AjaxParams;

import com.gem.talkbase.R;
import com.gem.talkbase.adapter.FirendRingAdapter;
import com.gem.talkbase.adapter.RecentChatAdapter;
import com.gem.talkbase.bean.Firend;
import com.gem.talkbase.bean.FirendMsg;
import com.gem.talkbase.bean.FirendRing;
import com.gem.talkbase.client.Client;
import com.gem.talkbase.service.JSON_FriendRing_info;
import com.gem.talkbase.service.JSON_Friend_info;
import com.gem.talkbase.util.T;
import com.gem.talkbase.util.Tool;
import com.gem.talkbase.widget.ExtendedListView;


import android.R.integer;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;

public class FirendRing_Activity extends Activity implements OnClickListener{  
   
	 public final static String PAR_KEY="com.gem.talkbase";
	 private String requestPath=Client.GetFirendRingInfo_URL,userid;
	private ImageView headImageView ;
	private Button upload ;
	private String[] items = new String[] { "选择本地图片" , "拍照" };
	SharedPreferences sharedPreferences; 
	List<FirendRing> list;
	List<FirendRing> list2=new ArrayList<FirendRing>();
	FirendRingAdapter firendringadapter;
	private ExtendedListView list_show_time = null;
	/* 请求码*/
	private static final int IMAGE_REQUEST_CODE = 0;
	private static final int CAMERA_REQUEST_CODE = 1;
	private static final int RESULT_REQUEST_CODE = 2;

	/*头像名称*/
	private static final String IMAGE_FILE_NAME = "faceImage.jpg";

    String date =  null,username,userimage ;
	private String urlPhoto = null; 


	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.firend_ring);
		
	    init();
		sharedPreferences = getSharedPreferences(Client.SAVE_USER,MODE_PRIVATE);
		userid = sharedPreferences.getString("userid", ""); //这 是登录者的手机号
		username =sharedPreferences.getString("username", ""); //这 是登录者的手机号
		userimage =sharedPreferences.getString("userimage", ""); //这 是登录者的手机号
		fun(userid,username,userimage);
 
	}
	public void fun(final String userid,final String username,final String userimage){
			
		AjaxParams params = new AjaxParams();
		params.put("userid", userid);//文字

		FinalHttp fh = new FinalHttp();
		fh.post(requestPath, params, new AjaxCallBack<String>() {
			@Override
			public void onFailure(Throwable t, String strMsg) {
				System.out.println("加载失败！！！");
				super.onFailure(t, strMsg);
			}
			@Override
			public void onLoading(long count, long current) {
				// TODO Auto-generated method stub
				System.out.println("正在加载！！！");
				super.onLoading(count, current);
			}
			
			@Override
			public void onSuccess(String jsonString) {
	 			super.onSuccess(jsonString);
            
	 			System.out.println(jsonString.toString()+"***********************");
				list=new ArrayList<FirendRing>();
				JSON_FriendRing_info json=new JSON_FriendRing_info();
				list= json.info(jsonString);
				System.out.println("111111111111111111111111111111111111111111111111111111");
				Iterator<FirendRing> iterator=list.iterator();
				String user_name,userimage1,edit,photoname,_time;
				while (iterator.hasNext()) {
					System.out.println("2222222222222222222222222222222222222222222");
					FirendRing firendRing = (FirendRing) iterator.next();
					user_name=firendRing.getUser_id();
					userimage1=firendRing.getUserimage();
					edit =firendRing.getEdit();
					photoname=firendRing.getPhotoname();
					_time=firendRing.get_time();
					FirendRing firendRing2=new FirendRing(user_name,userimage1,edit,photoname,_time);
					list2.add(firendRing2);
		
					System.out.println(userimage1+"===========>>>>"+edit+"-----"+photoname+"------"+_time);
				}
				firendringadapter=new FirendRingAdapter(FirendRing_Activity.this,list2,username,userimage,date);
				list_show_time.setAdapter(firendringadapter);
			}
		});
	
	}
	
	
	public void init(){
		headImageView=(ImageView)findViewById(R.id.paizhao);
		headImageView.setOnClickListener(this);
		list_show_time=(ExtendedListView) findViewById(R.id.list_show_time);
	}



	@Override
	public void onClick(View v) {
		System.out.println("11111111111111111111111111111111111111111111111111111");
		showDialog() ;  
		
	}
	
	/**
	 * 显示选择对话框
	 */
	private void showDialog() {
		new AlertDialog.Builder(this)
		.setTitle("设置头像")
		.setItems( items , new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				switch (which) {
				case 0:        //从图库选择
					System.out.println("选择图库————————————————————————————");
					Intent intentFromGallery = new Intent();
					intentFromGallery.setType("image/*"); // 设置文件类型
					intentFromGallery
					.setAction(Intent.ACTION_GET_CONTENT);
					startActivityForResult(intentFromGallery,
							IMAGE_REQUEST_CODE);
					break;
				case 1:       //拍照
					Intent intentFromCapture = new Intent(
							MediaStore.ACTION_IMAGE_CAPTURE);
					// 判断存储卡是否可以用，可用进行存储 ,
					//DCIM是安卓手机照片文件夹，这个文件夹会存储手机相机拍摄的照片，也会存储照片的略缩图文件、
					if ( Tool.hasSdcard()) {
                         date = time() ;
						//以当前时间给照片命名命名
						intentFromCapture.putExtra(
								MediaStore.EXTRA_OUTPUT,
								Uri.fromFile(new File(Environment
										.getExternalStorageDirectory()+File.separator+"DCIM",
										date+".jpg")));


						/*//文件的名字是自定义的  IMAGE_FILE_NAME= "faceImage.jpg" 
						intentFromCapture.putExtra(
								MediaStore.EXTRA_OUTPUT,
								Uri.fromFile(new File(Environment
										.getExternalStorageDirectory()+File.separator+"DCIM",
										IMAGE_FILE_NAME)));*/

					}
					System.out.println("选择拍照————————————————————————————");
					startActivityForResult(intentFromCapture,
							CAMERA_REQUEST_CODE);
					break;
				}
			}
		})
		.setNegativeButton("取消", new DialogInterface.OnClickListener() {

			@Override
			public void onClick(DialogInterface dialog, int which) {
				dialog.dismiss();
			}
		}).show();
	}

	/*
	 * 获取Android系统当前时间 ，把当前时间作为图片的名字
	 * 返回的是当前时间的字符串
	 * */
	String time() {      
		SimpleDateFormat sdf=new SimpleDateFormat("hh-mm-ss");    
		String date=sdf.format(new java.util.Date()); 
		System.out.println("当前时间-------"+date);
		return date ;
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (resultCode!= RESULT_CANCELED) {
			switch (requestCode) {
			case IMAGE_REQUEST_CODE:
				System.out.println("图库回调————————————————————");
				System.out.println("调用截图方法——————————————————————————————");
				startPhotoZoom(data.getData());
				break;
			case CAMERA_REQUEST_CODE:
				System.out.println("拍照回调————————————————————");
				if ( Tool.hasSdcard()) {
					File tempFile = new File(   //创建一个File文件，这个文件的路径是拍照时照片的路径
							Environment.getExternalStorageDirectory().toString()+File.separator
							+"DCIM"+File.separator+ IMAGE_FILE_NAME);  
					System.out.println("照相机拍摄的照片存放的位置 ： " + tempFile.getPath() ) ;
					
					System.out.println("调用截图方法——————————————————————————————");
					startPhotoZoom(Uri.fromFile(tempFile));
				} else {
					Toast.makeText(FirendRing_Activity.this, "未找到存储卡，无法存储照片！",
							Toast.LENGTH_SHORT).show();
				}
				break;

			case RESULT_REQUEST_CODE:  //保存剪切完图片
				if (data != null) {
					getImageToView(data);
				}
				break;
			}
			super.onActivityResult(requestCode, resultCode, data);
		}  
	}

	/**
	 * 裁剪图片方法实现
	 */
	public void startPhotoZoom(Uri uri) {

		Intent intent = new Intent("com.android.camera.action.CROP");
		intent.setDataAndType(uri, "image/*");
		System.out.println("图片路径uri----"+uri);
		urlPhoto = uri.getPath();
		System.out.println("图片路径urlPhoto----"+urlPhoto);
		// 设置裁剪
		intent.putExtra("crop", "true");
		// aspectX aspectY 是宽高的比例
		intent.putExtra("aspectX", 1);
		intent.putExtra("aspectY", 1);
		// outputX outputY 是裁剪图片宽高
		intent.putExtra("outputX", 200 );
		intent.putExtra("outputY", 200 );
		intent.putExtra("return-data", true);
		startActivityForResult(intent, 2);
	}

	/**   
	 * 保存裁剪之后的图片数据，可以自己设置剪切后图片保存的名字
	 */
	private void getImageToView(Intent data) {
		Bundle extras = data.getExtras();
		Bitmap photo = null;
		if (extras != null) {
			photo = extras.getParcelable("data");
			    date =time();
			try {
              
				//图片剪切后存放的路径  （/mnt/sdcard/+后边自己拼接）  my文件夹
				File file = new File(Environment.getExternalStorageDirectory().toString()+
						File.separator+"my"+File.separator+date+".jpg");
				urlPhoto = file.getPath();
				System.out.println("剪切后图片存放的位置是： "+urlPhoto);

				if(!file.getParentFile().exists()){
					file.getParentFile().mkdirs();
				}
				OutputStream out = new FileOutputStream(file);
				photo.compress(Bitmap.CompressFormat.PNG, 90, out);
			} catch (Exception e) {
				e.printStackTrace();
			}  
			
			Intent intent = new Intent(FirendRing_Activity.this , EditRingActivity.class) ;
		//	intent.putExtra("imagename", urlPhoto)  ;	
		     Bundle bundle=new Bundle();
		     bundle.putParcelable(PAR_KEY, photo);
		     bundle.putString("imagename", urlPhoto);
		     bundle.putString("photoname", date);
		     intent.putExtras(bundle);
		     startActivity(intent);
			 System.out.println("photo---222--"+ photo );
			System.out.println("图片流"+photo.toString());
			
		}
	}

	
	
	
}
